<template>
    <view class="cart-temp" :style="themeColor">
        <header-bar :config="config"></header-bar>
        <view class="main" v-if="token">
            <mescroll-uni :height="height" ref="mescrollRef" @init="mescrollInit" :down="downOption" @down="refresh"
                :up="upOption" @up="getData" @emptyclick="emptyClick">
                <view class="header-action-bar header-action-bar-title">
                    <text class="car-title">购物车</text>
                    <!-- <view
                        v-if="webInfo.IsSelectWarehouse && warehouseListdata.length > 1 && orderType != 24"
                        @click="WarehouseNameshow"
                        >{{ WarehouseName }}<uni-icons class="icon" type="arrowdown"></uni-icons
                    ></view> -->
                    <view class="collapse-wrapper">
                        <view @click="handleCollapse">{{ isCollapse ? "全部展开" : "全部折叠" }}</view>
                        <view class="line">|</view>
                        <text @click="handleChange">{{ isEdit ? "完成" : "编辑" }}</text>
                    </view>
                </view>
                <view class="cart-list" v-if="isLoadOk">
                    <cart-item v-for="(item, index) in datas" :ref="`cart_${index}`" :key="item.WarehouseId"
                        :selectData="selectData" :productInfo="item" :isEdit="isEdit" :orderType="orderType"
                        @upNum="upNum" @changeCheck="changeCheck" @checkboxChange="checkboxChange" @delTip="delTip"
                        @changeDirectCheck="changeDirectCheck">{{ item.name }}</cart-item>
                </view>
            </mescroll-uni>
        </view>
        <view class="main mescroll-empty" v-else>
            <image src="/static/img/empty.png"></image>
            <view>登录后同步您购物车中的商品</view>
            <view class="btn btn-success-hollow" @click="goLogin">去登录</view>
        </view>
        <cart-bottom-bar ref="cartBottomBar" :isHome="isHome" :isEdit="isEdit" :selectData="selectData"
            :isShowSelect="isShowSelect" :productInfo="datas" :isDirect="orderType == 24" @selectAll="selectAll"
            @delCart="delCart" @isSelectAllBack="isSelectAllBack"></cart-bottom-bar>

        <uni-popup ref="delTip" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="确定删除该商品?" :before-close="true" @close="close"
                @confirm="doDel"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="WarehouseTip" type="center" :animation="false" :mask-click="false">
            <view class="Warehouselist">
                <view class="pop-return-title">
                    <text>选择仓库</text>
                </view>
                <search-bar :placeholderText="placeholderText" :searchValue="searchKey"
                    @searchFn="searchFn"></search-bar>
                <scroll-view class="scroll-box" :scroll-y="true" :show-scrollbar="false">
                    <view class="w-list">
                        <view v-for="item in warehouseListdata" @click="selectWarehouse(item)">{{
                            item.WarehouseName
                        }}</view>
                    </view>
                </scroll-view>
                <image src="@/static/img/close_one.png" class="closeimg" @click="closePop"></image>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { mapMutations } from "vuex"
import storage from "@/uni-sub-base/utils/storage.js"
import cartItem from "@/components/cart/cart-item.vue"
import cartBottomBar from "@/components/cart/cart-bottom-bar.vue"
import searchBar from "@/components/common/search-bar.vue"
import { GetWarehouseList } from "@/service/api/warehouse.js"
import { getUserCarList, deleteUserCar, updateCart } from "@/utils/cartUtil.js"
import { getElementHeight } from "@/uni-sub-base/utils/elementUtil.js"
import { eventBus } from "@/utils/eventBus.js"
export default {
    components: {
        cartItem,
        cartBottomBar,
        searchBar,
    },
    props: {
        isHome: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            isEdit: false,
            isShowSelect: true,
            downOption: {
                use: true,
            },
            upOption: {
                empty: {
                    btnText: "立即购买",
                },
            },
            placeholderText: "请输入仓库名称",
            datas: [],
            isLoadOk: false,
            height: "",
            isEmpty: false,
            selectData: {
                proIds: [],
                ids: [],
            },
            isSelectAll: true,
            delPro: null,
            config: {
                title: "购物车",
                back: false,
                centerSlot: true,
                barPlaceholder: true,
                rightSlot: false,
                rightBtns: [
                    {
                        id: 1,
                        btnType: 1,
                        type: "编辑",
                    },
                ],
            },
            webInfo: {},
            warehouseListdata: [],
            WarehouseName: "",
            searchKey: "",
            token: "",
            orderType: "",
            isCollapse: false,
        }
    },
    created() {
        if (!this.isHome) {
            this.config.back = true
            this.$nextTick(() => {
                this.getListHeight()
            })
        }
        this.webInfo = storage.getCache("webInfo")
        this.token = storage.getCache("token")
    },
    onLoad(e) {
        this.orderType = Number(e.orderType)
    },
    mounted() {
        eventBus.$on("SET_CART", (msg) => {
            if (msg) {
                this.datas = msg
            }
            //购物车数据变化 更新UI
            this.upView()
            this.upBottom()
            if (this.isSelectAll) {
                this.selectAll(true)
            }
        })
        if (this.webInfo.IsSelectWarehouse == 1) {
            this.warehouseList()
        }
    },
    methods: {
        ...mapMutations(["UP_WARE_VIEW"]),
        //获取列表高度
        getListHeight() {
            //获取商品高度
            getElementHeight(this, ".main", (e) => {
                e = this.isHome ? e - 54 - uni.upx2px(120) : e - uni.upx2px(120)

                this.height = e + "px"
                this.isLoadOk = true
                this.$nextTick(() => {
                    this.refresh()
                })
            })
        },
        //获取数据
        getData() {
            setTimeout(() => {
                getUserCarList(true, this.orderType).then((res) => {
                    this.datas = res
                    if (res.length > 0) {
                        this.mescroll.endBySize(res.length, 1)
                    } else {
                        this.isEmpty = true
                        this.mescroll.endBySize(0, 0)
                    }
                    this.upBottom()
                    setTimeout(() => {
                        this.selectAll(true)
                    }, 500)
                })
            }, 100)
        },
        //更新UI
        upView() {
            if (this.mescroll) {
                this.mescroll.endBySize(this.datas.length, 1)
            }
        },
        //更新底栏
        upBottom() {
            if (this.$refs.cartBottomBar) {
                this.$refs.cartBottomBar.getTotal(this.datas)
            }
        },
        //刷新
        refresh() {
            this.mescroll.resetUpScroll()
        },
        //更新底栏数据
        upNum(e) {
            this.upBottom()
        },
        //去采购
        emptyClick() {
            if (this.orderType == 24) {
                // 直发仓
                this.easyGoHome()
            } else {
                this.easyGoProduct()
            }
        },
        //删除
        delCart(isClearAll) {
            if (isClearAll) {
                let ids = []
                this.datas.forEach((pro) => {
                    pro.SubItems.forEach((sub) => {
                        ids.push(String(sub.ID))
                    })
                })
                let param = {
                    ids: ids.join(","),
                }
                this.doDelCart(param)
            } else if (this.selectData.ids.length > 0) {
                let param = {
                    ids: this.selectData.ids.join(","),
                }
                this.doDelCart(param)
            }
        },
        //删除接口
        doDelCart(param) {
            uni.showLoading({
                title: "提交中",
            })
            deleteUserCar(param, this.orderType).then((res) => {
                if (res) {
                    uni.hideLoading()
                    // this.refresh()
                    this.isEdit = false
                    this.setBtnText()
                    this.selectData.ids = []
                }
            })
        },
        handleChange() {
            this.isEdit = !this.isEdit
            if (!this.isEdit) {
                this.setTreeSelect([])
            }
        },
        //全选
        selectAll(e) {
            // this.isSelectAll = e
            let ids = []
            if (e) {
                this.datas.forEach((pro) => {
                    pro.SubItems.forEach((sub) => {
                        if (this.isEdit) {
                            ids.push(String(sub.ID))
                        } else {
                            if (this.orderType == 24) {
                                ids.push(String(sub.ID))
                            } else {
                                if (this.getAppSet().NoCheckStock) {
                                    ids.push(String(sub.ID))
                                } else {
                                    if (sub.Amount <= sub.Stock) {
                                        ids.push(String(sub.ID))
                                    }
                                }
                            }
                        }
                        // if (this.orderType != 24) {
                        //     if (!this.getAppSet().NoCheckStock) {
                        //         if (sub.Amount <= sub.Stock) {
                        //             ids.push(String(sub.ID))
                        //         }
                        //     } else {
                        //         ids.push(String(sub.ID))
                        //     }
                        // } else {
                        //     ids.push(String(sub.ID))
                        // }
                    })
                })
            }
            this.setTreeSelect(ids)
        },
        //商品子项选择回调
        checkboxChange(e, id) {
            let values = e.detail.value
            if (values.length > 0) {
                this.selectData.ids.push(values[0])
            } else {
                this.selectData.ids.forEach((e, index) => {
                    if (e == id) {
                        this.selectData.ids.splice(index, 1)
                    }
                })
            }
            this.setTreeSelect(this.selectData.ids)
        },
        // //数据处理
        // setTreeSelect(ids) {
        //     console.log("ids:", ids)
        //     //去重
        //     const set = new Set(ids)
        //     ids = [...set]
        //     this.selectData = {
        //         ids: ids,
        //     }
        //     this.$forceUpdate()
        // },
        //单个商品全选or取消全选
        changeCheck(obj) {
            console.log("obj:", obj)
            let isSelect = obj.isSelect
            let proId = obj.proId
            let subIds = obj.subIds
            let warehouseId = obj.warehouseId
            if (isSelect) {
                //全选
                this.datas.forEach((e) => {
                    e.newSubItems.forEach((v) => {
                        if (v.WarehouseId == warehouseId && v.ProductId == proId) {
                            v.SubItems.forEach((sub) => {
                                this.selectData.ids.push(String(sub.ID))
                            })
                        }
                    })
                })
            } else {
                //取消全选
                for (var i = this.selectData.ids.length - 1; i >= 0; i--) {
                    let e = this.selectData.ids[i]
                    subIds.forEach((sub) => {
                        if (e == sub) {
                            this.selectData.ids.splice(i, 1)
                        }
                    })
                }
            }
            this.setTreeSelect(this.selectData.ids)
        },
        isSelectAllBack(e) {
            this.isSelectAll = e
        },
        close() {
            this.$refs.delTip.close()
        },
        doDel() {
            let obj = {
                ProductId: this.delPro.ProductId,
                Amount: 0,
                UnitId: this.delPro.UnitId,
                UnitName: this.delPro.DefaultUnit,
                skuId: this.delPro.SkuId,
                ratio: this.delPro.Ratio,
            }
            let param = []
            param.push(obj)
            updateCart(param, false, true, this.orderType).then((res) => { })
            this.close()
        },
        delTip(e) {
            this.delPro = e
            this.$refs.delTip.open()
        },
        rightClick(e) {
            if (e.id == 1) {
                this.isEdit = !this.isEdit
                this.setBtnText()
            }
        },
        setBtnText() {
            this.config.rightBtns[0].type = this.isEdit ? "完成" : "编辑"
        },
        closePop() {
            this.$refs.WarehouseTip.close()
        },
        WarehouseNameshow() {
            this.$refs.WarehouseTip.open()
        },
        warehouseList() {
            let path = "?searchKey=" + this.searchKey
            GetWarehouseList(path).then((res) => {
                if (res.State == 1) {
                    this.warehouseListdata = res.Data.reverse()
                    let warehouse = storage.getCache("warehouse")
                    if (warehouse) {
                        let warehouseData = res.Data.filter((item) => {
                            return item.WarehouseName == warehouse.WarehouseName
                        })
                        if (warehouseData.length > 0) {
                            this.WarehouseName = warehouse.WarehouseName
                        } else {
                            this.WarehouseName = res.Data[0].WarehouseName
                            storage.setCache("warehouse", res.Data[0])
                        }
                    } else {
                        this.WarehouseName = res.Data[0].WarehouseName
                        storage.setCache("warehouse", res.Data[0])
                    }
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        //搜索
        searchFn(searchKey) {
            this.searchKey = searchKey
            this.warehouseListdata = []
            this.warehouseList()
        },
        selectWarehouse(item) {
            storage.setCache("warehouse", item)
            this.WarehouseName = item.WarehouseName
            this.closePop()
            this.refresh()
            this.upWareView()
        },
        upWareView() {
            this.UP_WARE_VIEW(new Date().getTime())
        },
        goLogin() {
            let url = "/pages/login/loading?goLogin=true"
            uni.reLaunch({
                url: url,
            })
        },
        changeDirectCheck(obj) {
            let isSelect = obj.isSelect
            let proId = obj.proId
            let supplierId = obj.supplierId
            let subIds = obj.subIds
            if (isSelect) {
                //全选
                this.datas.forEach((supp) => {
                    if (supp.WarehouseId == obj.warehouseId) {
                        supp.SubItems.forEach((sub) => {
                            if (sub.SaleStatus == 1 || this.isEdit) {
                                this.selectData.ids.push(String(sub.ID))
                            }
                        })
                    }
                })
            } else {
                //取消全选
                for (var i = this.selectData.ids.length - 1; i >= 0; i--) {
                    let e = this.selectData.ids[i]
                    subIds.forEach((sub) => {
                        if (e == sub) {
                            this.selectData.ids.splice(i, 1)
                        }
                    })
                }
            }
            this.setTreeSelect(this.selectData.ids)
        },
        //数据处理
        setTreeSelect(ids) {
            console.log("===", ids)
            //去重
            const set = new Set(ids)
            ids = [...set]
            this.selectData = {
                ids: ids,
            }
            this.$forceUpdate()
        },
        handleCollapse() {
            this.isCollapse = !this.isCollapse
            // this.datas.forEach((_, index) => {
            //     this.$refs[`cart_${index}`][0].changeSpecShow(this.isCollapse)
            // })
            this.datas.forEach((item) => {
                item.newSubItems.forEach((v) => (v.specshow = !this.isCollapse))
            })
        },
    },
}
</script>

<style lang="scss" scoped>
.container {}

.cart-temp {}

.cart-list {
    padding: 0 $app-page-padding $app-page-padding $app-page-padding;
}

.car-title {
    font-weight: bold;
    font-size: 32rpx;
    color: $color-gray-1;
}

.Warehouselist {
    background: $color-white;
    border-radius: 20rpx;
    width: 600rpx;
    position: relative;

    .pop-return-title {
        display: flex;
        justify-content: center;
        padding: $app-page-padding 0 0 0;

        text {
            font-size: 34rpx;
        }
    }

    .closeimg {
        width: 64rpx;
        height: 64rpx;
        position: absolute;
        bottom: -96rpx;
        left: 50%;
        margin-left: -32rpx;
    }

    .scroll-box {
        max-height: 40vh;
    }

    .w-list {
        padding: 0 $app-page-padding $app-page-padding $app-page-padding;

        view {
            font-size: 28rpx;
            padding: $app-item-padding 0;
            border-bottom: 1rpx solid #ebebeb;
        }
    }
}

.mescroll-empty {
    box-sizing: border-box;
    width: 100%;
    padding: 80px 25px;
    text-align: center;

    image {
        width: 140px !important;
        height: 98px !important;
        display: block;
        margin: 0 auto;
    }

    view {
        font-size: 26rpx;
        color: gray;
    }

    .btn {
        width: 180rpx;
        margin: 0 auto;
        margin-top: 30rpx;
    }
}

.collapse-wrapper {
    display: flex;
    align-items: center;
    font-size: 28rpx;

    .line {
        margin: 0 28rpx;
        color: #cccccc;
    }

    text {
        font-size: 28rpx;
    }
}
</style>
